<template>
  <el-container>
    <el-main>
      <!-- 头部 -->
      <div class="header">
        <el-row class="header-bar">
          <el-text class="mx-1" size="large">库存变动记录</el-text>
        </el-row>
      </div>

      <!-- 库存变动记录表格 -->
      <el-table
          :data="inventoryChanges"
          style="width: 100%"
          :row-class-name="tableRowClassName"
      >
        <el-table-column prop="id" label="记录编号"></el-table-column>
        <el-table-column prop="materialName" label="材料名称"></el-table-column>
        <el-table-column prop="changeType" label="变动类型"></el-table-column>
        <el-table-column prop="changeQuantity" label="变动数量"></el-table-column>
        <el-table-column
            prop="changeTime"
            label="变动时间"
            :formatter="formatDate"
        ></el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="totalItems"
          layout="total, prev, pager, next, jumper"
          @current-change="fetchInventoryChanges"
          style="margin-top: 20px; text-align: right;"
      ></el-pagination>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";

// 定义库存变动数据的引用
const inventoryChanges = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return "";
  const date = new Date(cellValue);
  return date.toLocaleDateString();
};

// 获取库存变动数据
const fetchInventoryChanges = async (page = 1) => {
  try {
    const response = await axios.get("http://localhost:8005/materials-manage/change", {
      params: {
        page,
        size: pageSize.value,
      },
    });
    inventoryChanges.value = response.data.records;
    totalItems.value = response.data.total;
  } catch (error) {
    console.error("获取库存变动数据时出错:", error);
  }
};

// 设置表格行的动态样式类
const tableRowClassName = ({ row }) => {
  if (row.changeType === "增加") {
    return 'row-increase';
  } else if (row.changeType === "减少") {
    return 'row-decrease';
  }
  return '';
};

// 组件挂载时获取数据
onMounted(() => {
  fetchInventoryChanges(currentPage.value);
});
</script>

<style scoped>
.header {
  position: sticky;
  top: 0;
  background-color: #f5f5f5;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  z-index: 1000;
}

.el-main {
  padding: 20px;
  margin-left: 20px;
}

.el-table {
  width: 100%;
}

/* 绿色背景表示库存增加 */
.row-increase {
  background-color: #b5ffb5;
}

/* 红色背景表示库存减少 */
.row-decrease {
  background-color: #ff9494;
}
</style>
